/**
* @project admin-go-api
* @name sysLoginInfo
* @descriptions 登录日志服务层
* @author 寒锋
* @date 2023-12-22 14:26:41
 */

package service

import (
	"admin-go-api/api/dao"
	"admin-go-api/api/entity"
	"admin-go-api/common/response"
	"admin-go-api/common/util"
	"admin-go-api/constants"
	"admin-go-api/pkg/jwt"
	"fmt"
	"github.com/gin-gonic/gin"
	"strings"
	"time"
)

type ISysOperationLogService interface {
	GetSysOperationLogList(c *gin.Context, PageNum, PageSize int, Username, BeginTime, EndTime string)
	CreateSysOperationLog(c *gin.Context)
	DeleteSysOperationLogById(c *gin.Context, dto entity.SysOperationLogIdDto)
	BatchDeleteSysOperationLog(c *gin.Context, dto entity.BatchDeleteSysOperationLogDto)
	CleanSysOperationLog(c *gin.Context)
}

type SysOperationLogServiceImpl struct {
}

// GetSysOperationLogList 获取日志列表
func (s SysOperationLogServiceImpl) GetSysOperationLogList(c *gin.Context, PageNum, PageSize int, Username, BeginTime, EndTime string) {
	if PageSize < 1 {
		PageSize = 10
	}
	if PageNum < 1 {
		PageNum = 1
	}
	list, count := dao.GetSysOperationLogList(PageNum, PageSize, Username, BeginTime, EndTime)
	data := map[string]interface{}{"total": count, "pageNum": PageNum, "pageSize": PageSize, "rows": list}
	response.Success(c, data)
}

// CreateSysOperationLog 添加操作日志
func (s SysOperationLogServiceImpl) CreateSysOperationLog(c *gin.Context) {
	sysAdmin, _ := jwt.GetAdmin(c)
	data := entity.SysOperationLog{
		AdminId:    sysAdmin.AdminId,
		Username:   sysAdmin.Username,
		Method:     strings.ToLower(c.Request.Method),
		Ip:         c.ClientIP(),
		Url:        c.Request.URL.Path,
		CreateTime: util.HTime{Time: time.Now()},
	}
	dao.CreateSysOperationLog(data)
}

// DeleteSysOperationLogById 删除日志
func (s SysOperationLogServiceImpl) DeleteSysOperationLogById(c *gin.Context, dto entity.SysOperationLogIdDto) {
	result := dao.DeleteSysOperationLogById(dto)
	if result {
		response.Success(c, nil)
		return
	}
	response.Failed(c, int(constants.ApiCode.FAILED), fmt.Sprintf("删除失败"))
}

// BatchDeleteSysOperationLog 批量删除
func (s SysOperationLogServiceImpl) BatchDeleteSysOperationLog(c *gin.Context, dto entity.BatchDeleteSysOperationLogDto) {
	result := dao.BatchDeleteSysOperationLog(dto)
	if result {
		response.Success(c, nil)
		return
	}
	response.Failed(c, int(constants.ApiCode.FAILED), fmt.Sprintf("删除失败"))
}

// CleanSysOperationLog 清空日志
func (s SysOperationLogServiceImpl) CleanSysOperationLog(c *gin.Context) {
	result := dao.CleanSysOperationLog()
	if result {
		response.Success(c, nil)
		return
	}
	response.Failed(c, int(constants.ApiCode.FAILED), fmt.Sprintf("清空日志失败"))
}

var sysOperationLogService = SysOperationLogServiceImpl{}

func SysOperationLogService() ISysOperationLogService {
	return &sysOperationLogService
}
